using System;
using System.Collections;
using Game;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace GameCore.UI
{
    public class ProgressBarIcon : MonoBehaviour
    {
        public float progress;
        public Image image;
        public TMP_Text text;
        public ProgressBar bar;

        public void SetSprite(Sprite sprite)
        {
            image.sprite = sprite;
        }

        public void SetProgress(int progress)
        {
            this.progress = progress;
        }

        public void SetProgress(int progress, float time)
        {
            StartCoroutine(TweenProgress(progress, time));
        }

        private IEnumerator TweenProgress(int target, float time)
        {
            var stepSize = (target - progress) / time;
            var t = 0f;
            while (t < time)
            {
                progress += stepSize * Time.deltaTime;
                t += Time.deltaTime;
                Refresh();
                yield return null;
            }
            progress = target;
            Refresh();
        }

        public void Refresh()
        {
            var pct = progress / bar.total;
            var rt = transform as RectTransform;
            rt.anchorMin = new Vector2(pct, 0.5f);
            rt.anchorMax = new Vector2(pct, 0.5f);
            rt.anchoredPosition = Vector2.zero;
            rt.pivot = new Vector2(0.5f, 0.5f);
            text.text = ((int)progress).ToString();
        }
        
        #if UNITY_EDITOR
        private void OnValidate()
        {
            Refresh();
        }
        #endif
    }
}